package org.example.filter;

/**
 * @Description
 * @Author chenhs
 * @Date 14:43 2025/7/26
 */

import org.example.util.JwtUtil;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;
import io.jsonwebtoken.Claims;

@Component
public class AuthFilter extends AbstractGatewayFilterFactory<AuthFilter.Config> {

    public AuthFilter() {
        super(Config.class);
    }

    @Override
    public GatewayFilter apply(Config config) {
        System.out.println("123123123");
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();

            // 1. 检查是否在白名单
            String path = request.getPath().toString();
            if (path.contains("/users/hello")) {
                return chain.filter(exchange);
            }

            // 2. 获取token
            String token = request.getHeaders().getFirst("Authorization");
            if (token == null || !token.startsWith("Bearer ")) {
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                return exchange.getResponse().setComplete();
            }

            // 3. 验证token
            try {
                String jwt = token.substring(7);
                Claims claims = JwtUtil.parseToken(jwt);

                // 4. 添加用户信息到header
                ServerHttpRequest modifiedRequest = request.mutate()
                        .header("X-User-Info", claims.getSubject())
                        .header("X-User-Role", claims.get("role", String.class))
                        .build();

                // 5. 检查管理员权限
                if (path.contains("/admin") && !"admin".equals(claims.get("role"))) {
                    exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
                    return exchange.getResponse().setComplete();
                }

                return chain.filter(exchange.mutate().request(modifiedRequest).build());
            } catch (Exception e) {
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                return exchange.getResponse().setComplete();
            }
        };
    }

    public static class Config {
        private String secretKey;

        public String getSecretKey() {
            return secretKey;
        }

        public void setSecretKey(String secretKey) {
            this.secretKey = secretKey;
        }
    }
}